package action;

/**
 * 根据浏览器所有提交到此处的cartitem表中的id到数据库cartitem表中查询出对应所有的图书
 */

import dao.CartItemDao;
import dao.OrderDao;
import dao.OrderItemDao;
import po.Order;
import po.OrderItem;
import po.User;
import utils.DateCoverter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

@WebServlet(urlPatterns = "/user/action/CartToOrderServlet")
public class CartToOrderServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String itemIdsString = req.getParameter("itemIds");
        String [] itemIds = itemIdsString.split(",");
        User user = (User) req.getSession().getAttribute("user");
        CartItemDao cartItemDao = new CartItemDao();
        ArrayList<HashMap<String,Object>> list = cartItemDao.selectCartItemAssociatedBook(itemIds);
        Order order = new Order();
        order.setOrderId(user.getPhone().substring(user.getPhone().length()-3) + DateCoverter.formatTimeStamp(new Date()));
        order.setUserId(user.getPhone());
        order.setSta("待处理");
        OrderDao orderDao = new OrderDao();
        orderDao.insert(order);
        OrderItem orderItem = null;
        OrderItemDao orderItemDao = new OrderItemDao();
        //加强for循环
        for (HashMap<String,Object> map : list){
            orderItem = new OrderItem();
            orderItem.setOrderId(order.getOrderId());
            orderItem.setProduct((String) map.get("product"));
            orderItem.setCount((Integer)map.get("count"));
            orderItem.setPrice((Double)map.get("price"));
            orderItemDao.insert(orderItem);
        }
        resp.sendRedirect("../action/OrderConfirmServlet?orderId="+order.getOrderId());
    }
}
